package com.cofdet.modbusdebugger;

import android.content.Intent;
import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

public class UdpClient implements Runnable{
    private int ServerPort;
    private String ServerIp;
    private static DatagramSocket socket = null;
    private static DatagramPacket packetSend,packetRcv;
    private boolean udpLife = true; //udp生命线程
    private boolean udpLifeOver = true; //生命结束标志，false为结束
    private boolean isOnlyServer = true; //是否只接收服务器的接入

    private byte[] msgRcv = new byte[4096]; //接收消息

    private final ModbusCfg modbusCfg;

    public UdpClient(String mIp, int mPort, ModbusCfg modbusCfg){
        //this.ServerIp  = "192.168.88.212";//测试时
        this.ServerIp = mIp;
        this.ServerPort = mPort;
        this.modbusCfg = modbusCfg;
    }

    //返回udp生命线程因子是否存活
    public boolean isUdpLife(){
        if (udpLife){
            return true;
        }
        return false;
    }

    //更改UDP生命线程因子
    public void setUdpLife(boolean b){
        udpLife = b;
    }
    //返回具体线程生命信息是否完结
    public boolean IsUdpLifeOver(){
        return udpLifeOver;
    }
    //发送消息
    public void send(String msg){
        ByteBuffer wrBuf = ByteBuffer.allocate(4096);
        modbusCfg.SendPro(wrBuf, msg);

        InetAddress hostAddress = null;
        try {
            hostAddress = InetAddress.getByName(ServerIp);
        } catch (UnknownHostException e) {
            Log.i("UdpClient","未找到服务器");
            e.printStackTrace();
        }
        packetSend = new DatagramPacket(wrBuf.array(), wrBuf.limit(), hostAddress, ServerPort);
        try {
            socket.send(packetSend);
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("UdpClient","发送失败");
        }
    }

    @Override
    public void run() {
        try {
            socket = new DatagramSocket(ServerPort);//暂与发送端口相同
            socket.setSoTimeout(3000);//设置超时为3s
        } catch (SocketException e) {
            Log.i("UdpClient","建立接收数据报失败");
            e.printStackTrace();
        }
        packetRcv = new DatagramPacket(msgRcv,msgRcv.length);
        while (udpLife){
            try {
                Log.i("UdpClient", "UDP监听");
                socket.receive(packetRcv);
                //收到数据了,将收到的消息发给主界面
                System.arraycopy(msgRcv, packetRcv.getOffset(), msgRcv, 0, packetRcv.getLength());//去掉前缀
                String rcvMsg = modbusCfg.RcvPro(msgRcv, packetRcv.getLength());
                String curIP = packetRcv.getAddress().getHostAddress().toString();
                //实际可以接收任何服务器的接入，如果判断服务器IP时，可只接收服务器的接入。
                if(isOnlyServer == true) {//比较IP
                    if(curIP.equals(ServerIp))
                        rcvMsg = "Rx: " + rcvMsg;
                    else rcvMsg = "RxErr: " + curIP + "异常接入!";
                }
                else{//接收任何IP时指定接收的谁的
                    rcvMsg = curIP + "Rx: " + rcvMsg;
                }
                Log.i("SocketInfo", rcvMsg);
                Intent intent = new Intent();
                intent.setAction("tcpServerReceiver");
                intent.putExtra("tcpServerReceiver", rcvMsg);
                FuncTcpServer.context.sendBroadcast(intent);//将消息发送给主界面
            }catch (IOException e){
                e.printStackTrace();
            }
        }

        Log.i("UdpClient","UDP监听关闭");
        socket.close();
        udpLifeOver = false;
    }
}